<?php
namespace app\index\controller;

use think\Request;
use think\facade\Db;
use think\admin\Controller;
use app\goods\model\ImsEweiShopGoods;
use think\facade\Filesystem;
use EasyWeChat\MiniApp\Application;
use app\wechat\service\WechatService;
use app\order\model\ImsEweiShopOrder;
use app\order\model\ImsEweiShopOrderGoods;

class Test extends Controller
{
    public function index(){
        $a = "清风🍺 🍺 明月";
        echo filterWechatNickname($a);
        $orderWhere['status'] = [2,30];
        $data = ImsEweiShopOrder::mk()->where($orderWhere)->order('id desc')->select()->toArray();
        var_dump($data);exit();
        
    }

    public function getOpenidPhone(){

    }

    public function category(){
        /////////////////////////////////分类整理///////////////////////////////
        $list_1 = Db::table('ims_ewei_shop_category')->where('pid','=',0)->limit(0,100)->select()->toArray();
        foreach ($list_1 as $k => $v) {
            if ($v['level'] != 1) {
                // echo $v['level'];exit();
                Db::table('ims_ewei_shop_category')->where('id','=',$v['id'])->save(['level'=>1]);
            }
            $list_2 = Db::table('ims_ewei_shop_category')->where('pid','=',$v['id'])->limit(0,100)->select()->toArray();
            foreach ($list_2 as $kk => $vv) {
                if ($vv['level'] != 2) {
                    // echo $vv['name'];exit();
                    Db::table('ims_ewei_shop_category')->where('id','=',$vv['id'])->save(['level'=>2]);
                }
                $list_3 = Db::table('ims_ewei_shop_category')->where('pid','=',$vv['id'])->limit(0,100)->select()->toArray();
                foreach ($list_3 as $kkk => $vvv) {
                    if ($vvv['level'] != 3) {
                        // echo $vvv['name'];exit();
                        Db::table('ims_ewei_shop_category')->where('id','=',$vvv['id'])->save(['level'=>3]);
                    }
                }
            }
        }
        /////////////////////////////////分类整理///////////////////////////////
    }

    public function openid(){
        $code = $this->request->post('code')?'0a3C2O100C7w3U1pdM000tCPLr1C2O15':'0a3C2O100C7w3U1pdM000tCPLr1C2O15';
        //配置后期加在env里或者config
        $config_arr = WechatService::getWxconf();
        $config = [
            'app_id' => $config_arr['appid'],
            'secret' => $config_arr['appsecret'],
            'mch_id' => $config_arr['appsecret'],
            'log' => [
                'level' => 'debug',
            ]
        ];

        $app = new Application($config);
        $result = [];
        $api = $app->getClient();
        $api_url = 'https://api.weixin.qq.com/sns/jscode2session';
        // 3. 准备数据
        $deliveryData = [
            "appid" => $config['app_id'],
            "secret" => $config['secret'],
            "js_code" => $code,
            "grant_type" => 'authorization_code'
        ];
        $result = $api->get($api_url, $deliveryData );
        if (isset($result['errcode'])) {
            var_dump($result['errcode']);exit();
        }else{
            $openid = $result['openid'];
        }
        var_dump($result['openid']);exit();
    }

    public function wechattest(){
        // $rfc3339 = date('Y-m-d\TH:i:sP');
        // echo $rfc3339;exit();
        //配置后期加在env里或者config
        $config_arr = WechatService::getWxconf();
        $config = [
            'app_id' => $config_arr['appid'],
            'secret' => $config_arr['appsecret'],
            'mch_id' => $config_arr['appsecret'],
            'log' => [
                'level' => 'debug',
            ]
        ];

        $app = new Application($config);
        
        try {
            // 1. 获取请求参数
            $params = request()->post();
            
            $orderid = $this->get['id'] ?? '0';
            $orderinfo = ImsEweiShopOrder::mk()->where(['ordersn'=>'ME20250416150836462889'])->find()->toArray();

            $orderGoodList = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$orderinfo['id']])->select();
            $item_desc = '';
            foreach ($orderGoodList as $k => $v) {
                $item_desc .= $v['title'].';';
            }
            // var_dump($item_desc);exit();
            // 2. 验证必要参数
            if (empty($orderinfo['ordersn']) || empty($orderinfo['openid']) || empty($orderinfo['transid'])) {
                throw new \Exception('缺少必要参数');
            }
            
            $record = Db::table('wechat_payment_record')->where('payment_trade','=',$orderinfo['transid'])->find();
            // var_dump($record);exit();
            $accessToken = $app->getAccessToken();
            $access_token = $accessToken->getToken(); // string
            $api = $app->getClient();

            // //发货
            // $url_send = "https://api.weixin.qq.com/shop/delivery/send?access_token=".$access_token;
            // $orderDetail = [
            //     "out_order_no" => $record['code'],
            //     "openid" => $orderinfo['openid'],
            //     "finish_all_delivery" => 1,
            //     "delivery_list" => [
            //         'delivery_id'=> 'OTHERS',
            //         'waybill_id'=> $orderinfo['ordersn']
            //     ]
                
            // ];
            // $result = $api->post($url_send, [
            //         'json' => json_encode($orderDetail)
            //     ]
            // );
            // dump($url_send);
            // dump($orderDetail);

            // var_dump($result['errcode']);

            // var_dump($result['errmsg']);exit();



            ////上传购物详情数据
           // $url_o = "https://api.weixin.qq.com/user-order/orders?access_token=".$access_token;

			$url_o = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=".$access_token;
            		//	echo $url_o;


		
            $orderDetail = [
                "order_key" => [
                    "order_number_type" => 2,
                    "transaction_id" => $record['payment_trade'],
                    "mchid"=>"1711684005",
                    "out_trade_no"=>$record['code']
                ],
               /*"order_list" => [
                    [
        				"merchant_order_no" =>  $record['code'],
        				"order_detail_jump_link" =>[							
        					"url"=> "https://www.weixin.qq.com/wxpay/pay.php",
        					"appid"=> $config_arr['appid'],
        					"path"=> "/modules/userModule/pages/userordersinfo/userordersinfo",
        					"type"=> 2
        				]
                    ],
                ],*/



				"logistics_type" => 2,
				"delivery_mode" => 1,

					 "shipping_list" => [
                    [
						 "item_desc" => "测试"
                        //"tracking_no"=> $orderinfo['ordersn'],
                       // "express_company"=>"OTHERS",
                    ]
                ],

                "upload_time" => date('Y-m-d\TH:i:sP'),//"2022-12-15T13:29:35.120+08:00"
                "payer" => [
                    'openid'=>$orderinfo['openid']
                ]
				
            ];
			

			$result = $api->post($url_o, [
                    'json' => json_encode($orderDetail)
                ]
            );
			dump($orderDetail);

			var_dump($result['errcode']);

            var_dump($result['errmsg']);exit();





            $api_url = 'https://api.weixin.qq.com/user-order/orders/shippings?access_token='.$access_token;

            // 3. 准备发货数据
            $deliveryData = [
                "order_key" => [
                    "order_number_type" => 2,
                    "transaction_id" => $record['payment_trade'],
                    "mchid"=>"1711684005",
                    "out_trade_no"=>$record['code']
                ],
                "delivery_mode" => 1,
                "logistics_type" => 2,
                "shipping_list" => [
                    [
                        "tracking_no"=> $orderinfo['ordersn'],
                        "express_company"=>"OTHERS",
                    ]
                ],
                "upload_time" => date('Y-m-d\TH:i:sP'),//"2022-12-15T13:29:35.120+08:00"
                "payer" => [
                    'openid'=>$orderinfo['openid']
                ]
            ];
            $result = $api->post($api_url, [
                    'json' => json_encode($deliveryData)
                ]
            );
            dump($api_url);

            dump($deliveryData);
            
			dump($result['errcode']);

            var_dump($result['errmsg']);exit();
            // 5. 处理返回结果
            if ($result['errcode'] != 0) {
                return json(['code' => 0, 'msg' => '发货失败：' . $result['errmsg']]);
            }
            
            // 6. 更新本地订单状态
            // $this->updateOrderStatus($params['order_id'], 'shipped');
            
            return json(['code' => 1, 'msg' => '发货成功', 'data' => $result]);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
        exit();
    }

    public function wechatsc(){
        // $rfc3339 = date('Y-m-d\TH:i:sP');
        // echo $rfc3339;exit();
        //配置后期加在env里或者config
        $config_arr = WechatService::getWxconf();
        $config = [
            'app_id' => $config_arr['appid'],
            'secret' => $config_arr['appsecret'],
            'mch_id' => $config_arr['appsecret'],
            'log' => [
                'level' => 'debug',
            ]
        ];

        $app = new Application($config);
        
        try {
            // 1. 获取请求参数
            $params = request()->post();
            
            $orderid = $this->get['id'] ?? '0';
            $orderinfo = ImsEweiShopOrder::mk()->where(['ordersn'=>'ME20250410162611188622'])->find()->toArray();

            $orderGoodList = ImsEweiShopOrderGoods::mk()->where(['orderid'=>$orderinfo['id']])->select();
            $item_desc = '';
            foreach ($orderGoodList as $k => $v) {
                $item_desc .= $v['title'].';';
            }
            // var_dump($item_desc);exit();
            // 2. 验证必要参数
            if (empty($orderinfo['ordersn']) || empty($orderinfo['openid']) || empty($orderinfo['transid'])) {
                throw new \Exception('缺少必要参数');
            }
            
            $record = Db::table('wechat_payment_record')->where('payment_trade','=',$orderinfo['transid'])->find();
            // var_dump($record);exit();
            $accessToken = $app->getAccessToken();
            $access_token = $accessToken->getToken(); // string
            $api = $app->getClient();
            $api_url = 'https://api.weixin.qq.com/user-order/orders?access_token='.$access_token;

            // 3. 准备发货数据
            $deliveryData = [
                "order_key" => [
                    "order_number_type" => 2,
                    "transaction_id" => $record['payment_trade'],
                    "mchid"=>"1711684005",
                    "out_trade_no"=>$record['code']
                ],
                "order_list" => [
                    [
                        "merchant_order_no"=> $orderinfo['ordersn'],
                        "order_detail_jump_link"=>"DHL",
                    ]
                ],
                "delivery_mode" => 1,
                "logistics_type" => 2,
                
                "upload_time" => date('Y-m-d\TH:i:sP'),//"2022-12-15T13:29:35.120+08:00"
                "payer" => [
                    'openid'=>$orderinfo['openid']
                ]
            ];
            $result = $api->post($api_url, [
                    'json' => json_encode($deliveryData)
                ]
            );
            var_dump($result['errmsg']);exit();
            // 5. 处理返回结果
            if ($result['errcode'] != 0) {
                return json(['code' => 0, 'msg' => '发货失败：' . $result['errmsg']]);
            }
            
            // 6. 更新本地订单状态
            // $this->updateOrderStatus($params['order_id'], 'shipped');
            
            return json(['code' => 1, 'msg' => '发货成功', 'data' => $result]);
            
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
        exit();
    }
}
        